import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:pornhub_app/components/image_view.dart';
import 'package:pornhub_app/components/easy_toast.dart';
import 'package:pornhub_app/env/environment_service.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/services/app_service.dart';
import 'package:pornhub_app/services/storage_service.dart';
import 'package:pornhub_app/utils/ad_jump.dart';
import 'package:pornhub_app/utils/enum.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/utils/initAdvertisementInfo.dart';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../assets/assets.dart';
import '../../assets/styles.dart';

class Step2Page extends StatefulWidget {
  const Step2Page({super.key});
  @override
  State<StatefulWidget> createState() {
    return LaunchState();
  }
}

class LaunchState extends State<Step2Page> {
  late Timer _timer;
  final _currentTimer = ValueNotifier<int>(5);

  final startAd = initWeightAdvertisementInfo(AdPlaceNameEnum.START);

  @override
  void initState() {
    _timer = Timer.periodic(
      const Duration(milliseconds: 1000),
      (timer) {
        if (_currentTimer.value > 0) {
          _currentTimer.value -= 1;
        }
      },
    );
    super.initState();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  Widget _buildAds() {
    if (startAd == null) {
      return Positioned.fill(
        child: Image.asset(
          Assets.splash,
          width: Get.width,
          height: Get.height,
          fit: BoxFit.fill,
        ),
      );
    }
    return Positioned.fill(
      child: ImageView(
        width: Get.width,
        height: Get.height,
        src: startAd!.adImage ?? '',
        fit: BoxFit.fill,
        defaultPlace: Assets.splash,
      ).onTap(
        () {
          kAdjump(startAd!, startAd!.adId);
        },
      ),
    );
  }

  void _tapJumpAction() async {
    if (_currentTimer.value == 0) {
      // final networkInitCompleter = Get.find<AppService>().networkInitCompleter;
      // if (networkInitCompleter.isCompleted) {
      //   final err = await networkInitCompleter.future;
      //   if (err != null) {
      //     EasyToast.show("初始化失败,请退出重试!");
      //     return;
      //   }
      // } else {
      //   // 如果请求还未结束，转个圈圈?
      //   EasyToast.show("初始化中，请稍候.");
      //   return;
      // }

      // final hasToken = Get.find<StorageService>().token?.isNotEmpty;
      // if (GetPlatform.isWeb) {
      //   if (hasToken == false) {
      //     EasyToast.show("初始化失败,请退出重试!");
      //     return;
      //   }
      // } else {
      //   if (hasToken == false || Environment.androidiOSAPI.isEmpty) {
      //     EasyToast.show("初始化失败,请退出重试!");
      //     return;
      //   }
      // }
      Get.offHome();
    }
  }

  Widget _buildBtn() {
    return !GetPlatform.isWeb && Environment.androidiOSAPI.isEmpty
        ? const SizedBox.shrink()
        : Positioned(
            right: 15.w,
            top: kIsWeb ? 25.w : 60.w,
            child: ValueListenableBuilder(
              valueListenable: _currentTimer,
              builder: (context, value, child) {
                return Container(
                  width: 75.w,
                  decoration: BoxDecoration(
                      color: const Color.fromRGBO(0, 0, 0, 0.7),
                      borderRadius: Styles.borderRadius.m),
                  padding: const EdgeInsets.only(top: 8, bottom: 5),
                  alignment: Alignment.center,
                  child: Text(
                    _currentTimer.value > 0 ? '${_currentTimer.value}' : '跳过',
                    style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 16.w,
                        color: Colors.white),
                    strutStyle: const StrutStyle(forceStrutHeight: true),
                  ),
                ).onTap(_tapJumpAction);
              },
            ),
          );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox(
        width: Get.width,
        height: Get.height,
        child: Stack(
          children: [
            _buildAds(),
            _buildBtn(),
          ],
        ),
      ),
    );
  }
}
